#pragma once
#include "stdafx.h"
#include "mySQLTool.h"

mySQLTool stc_SQL;

mySQLTool::mySQLTool()
{
	m_IsRuning = false;
	memset(&m_DB, 0, sizeof(m_DB));

	mysql_init(&m_DB);
	mysql_options(&m_DB, MYSQL_SET_CHARSET_NAME, "gbk");
}

mySQLTool::~mySQLTool()
{

}

bool mySQLTool::ConnectDB(char *Host, UINT Port, char *DBName, char *Account, char *PassWord)
{
	if (NULL == Host || NULL == DBName || NULL == Account || NULL == PassWord)
	{
		return false;
	}

	m_Host = Host;
	m_Name = DBName;
	m_Account = Account;
	m_Password = PassWord;
	m_Port = Port;

	MYSQL *Res = mysql_real_connect(&m_DB, 
		Host, 
		Account, 
		PassWord, 
		DBName, 
		Port, 
		NULL, 
		NULL);

	if (NULL == Res)
	{
		return false;
	}
	else
	{
		m_IsRuning = true;
		return true;
	}
}

bool mySQLTool::CloseDB()
{
	mysql_close(&m_DB);
	m_IsRuning = false;
	return true;
}

bool mySQLTool::IsRuning()
{
	if (false == m_IsRuning)
	{
		return false;
	}

	if (0 != mysql_ping(&m_DB))
	{
		return false;
	}
	else
	{
		return true;
	}
}

int mySQLTool::RunSQL(char *SQLMsg, bool Back /* = false */)
{
	int Res = mysql_query(&m_DB, SQLMsg);
	if (0 != Res)
	{
		return false;
	}

	if (true == Back)
	{
		m_DBQuery = mysql_store_result(&m_DB);
		if (NULL == m_DBQuery)
		{
			return false;
		}
	}

	return true;
}

bool mySQLTool::GetRecord()
{
	m_DBRow = mysql_fetch_row(m_DBQuery);
	if (NULL == m_DBRow)
	{
		return false;
	}
	else
	{
		return true;
	}
}

bool mySQLTool::FreeSQL()
{
	mysql_free_result(m_DBQuery);
	return true;
}

DWORD mySQLTool::GetFieldNum()
{
	return mysql_num_fields(m_DBQuery);	
}

SINT mySQLTool::GetRowNum()
{
	return mysql_num_rows(m_DBQuery);
}

int mySQLTool::GetFieldName(int Num, char *OutName)
{
	if (Num <= 0 || NULL == OutName)
	{
		return -1;
	}

	m_Field = mysql_fetch_field_direct(m_DBQuery, Num);
	strcpy(OutName, m_Field->name);
	return 0;
}

int mySQLTool::GetFieldId(char *Name)
{
	if (NULL == Name)
	{
		return -1;
	}

	int Count = mysql_num_fields(m_DBQuery);
	if (Count <= 0)
	{
		return -1;
	}

	for (int i = 0; i < Count; ++ i)
	{
		char szName[512] = {0};
		GetFieldName(i, szName);

		if (0 == strcmp(Name, szName))
		{
			return i;
		}
	}

	return -1;
}

void mySQLTool::GetLastError(char *Msg)
{
	strcpy_s(Msg, sizeof(char) * 1024, mysql_error(&m_DB));
	return;
}

const char* mySQLTool::GetLastError()
{
	return mysql_error(&m_DB);
}